import { defineComponent, ref, toRaw, watch } from 'vue'
import { Tree, Input, Checkbox } from 'ant-design-vue'
import type { TreeProps } from 'ant-design-vue'
import './index.less'
import PropTypes from '@/utils/PropTypes'
import Icon from '../Icon'
import { debounceFunc } from '@/utils/lodash'
type T = {
  title: string
  children: string
  key: string
  topkey: string
}
export default defineComponent({
  name: 'OriginTree',
  props: {
    showSearch: PropTypes.bool().def(true),
    treeData: PropTypes.array().def([]),
    checkable: PropTypes.bool().def(true),
    checkStrictly: PropTypes.bool().def(false),
    fieldName: PropTypes.object<T>().def({
      title: 'title',
      children: 'children',
      key: 'key',
      topkey: 'parentId',
    }),
    backGround: PropTypes.string().def('#fff'),
    hight: PropTypes.number(),
    checkedKeys: PropTypes.array<string>().def([]),
  },
  emits: ['update:checkedKeys'],
  setup(props, { emit }) {
    const { title, children, key, topkey } = toRaw(props.fieldName)
    const treeDatas = ref<any[]>([])
    const searchValue = ref<string>('')
    const expandedKeys = ref<string[]>([])
    const checkedKeys = ref<string[]>([])

    const handelKeys = (treeData: any[]) => {
      treeData.forEach((item: any) => {
        expandedKeys.value.push(item[key])
        if (item[children] && item[children].length > 0) {
          handelKeys(item[children])
        }
      })
    }

    // 机构树形数据
    const getParentKey = (key: string | number, tree: any) => {
      for (let i = 0; i < tree?.length; i++) {
        const node = tree[i]
        if (node && node[title].indexOf(key) > -1) {
          expandedKeys.value.push(node.topkey)
          topkey && expandedKeys.value.push(topkey)
          if (
            node[children] &&
            Array.isArray(node[children]) &&
            node[children].length > 0
          ) {
            const flag = getParentKey(key, node[children])
            console.log(flag, '11')
          }
          return true
        } else {
          const flag = getParentKey(key, node[children])
          if (flag) return true
        }
      }
    }
    const onCheck: TreeProps['onCheck'] = (hascheckedKeys: any, info: any) => {
      if (!props.checkStrictly) {
        console.log(hascheckedKeys, info, 'info')

        localStorage.halfCheckedKeys = JSON.stringify(info.halfCheckedKeys)
        // const isCheckedKeys = [...info.halfCheckedKeys!, ...hascheckedKeys]
        const isCheckedKeys = hascheckedKeys
        emit('update:checkedKeys', isCheckedKeys)
      } else {
        localStorage.halfCheckedKeys = JSON.stringify(
          hascheckedKeys.halfChecked,
        )
        const isCheckedKeys = [
          ...hascheckedKeys.halfChecked!,
          ...hascheckedKeys.checked,
        ]
        emit('update:checkedKeys', isCheckedKeys)
      }
    }
    const handelSearch = (val: string): any => {
      if (val) {
        treeDatas.value = treeDatas.value
          .map((item: any) => {
            if (item[title].indexOf(val) > -1) {
              expandedKeys.value.push(item[key])
              return item
            } else {
              const flag = getParentKey(val, item[children])
              if (flag) return item
            }
          })
          .filter((obj) => obj)
      } else {
        searchValue.value = ''
        expandedKeys.value = []
        treeDatas.value = props.treeData
      }
    }

    watch(
      () => props.treeData,
      () => {
        treeDatas.value = props.treeData
        handelKeys(treeDatas.value)
        checkedKeys.value[0] = treeDatas.value[0][key]
        emit('update:checkedKeys', checkedKeys.value)
      },
    )
    watch(
      () => searchValue.value,
      (val) => {
        debounceFunc(() => handelSearch(val))
      },
    )
    watch(
      () => props.checkedKeys.length,
      () => {
        checkedKeys.value = props.checkedKeys
      },
    )
    return () => (
      <div class="OriginTree">
        {props.showSearch && (
          <Input
            v-model:value={searchValue.value}
            size="small"
            v-slots={{
              suffix: () => <Icon icon="search" colors="#9e9e9e" />,
            }}
            style={{ marginBottom: '10px' }}
          ></Input>
        )}
        <Tree
          v-model:expandedKeys={expandedKeys.value}
          v-model:checkedKeys={checkedKeys.value}
          tree-data={treeDatas.value}
          field-names={props.fieldName}
          checkable={props.checkable}
          checkStrictly={props.checkStrictly}
          onCheck={onCheck}
          style={{
            backgroundColor: props.backGround,
            height: props.hight + 'px',
          }}
          class="treeClass"
        ></Tree>
      </div>
    )
  },
})
